package com.planshare.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.json.rpc.client.HttpJsonRpcClientTransport;
import org.json.rpc.client.JsonRpcInvoker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.planshare.object.AndroidPlan;
import com.planshare.service.PlanService;
import com.planshare.util.UserUtil;

public class AddPlanActivity extends FragmentActivity {
	
	static EditText time;
	static EditText date;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_plan);
		
		time = (EditText) findViewById(R.id.time);
		date = (EditText) findViewById(R.id.date);
	}

	public static class TimePickerFragment extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute, true);
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			time.setText(hourOfDay + ":" + minute);
		}
	}

	public static class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			final Calendar c = Calendar.getInstance();
			c.set(year, month, day);
			SimpleDateFormat format_date = new SimpleDateFormat("MMM d, yyyy");
			date.setText(format_date.format(c.getTime()));
		}
	}
	
	public void showDatePickerDialog(View v) {
	    DialogFragment newFragment = new DatePickerFragment();
	    newFragment.show(getSupportFragmentManager(), "datePicker");
	}
	
	public void showTimePickerDialog(View v) {
	    DialogFragment newFragment = new TimePickerFragment();
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}
	
	public void addPlan(View v) {
		String name = ((EditText) findViewById(R.id.name)).getText().toString();
		if (name == null) {
			return;
		}
		String location = ((EditText) findViewById(R.id.location)).getText().toString();
		if (location == null) {
			return;
		}
		String description = ((EditText) findViewById(R.id.description)).getText().toString();
		if (description == null) {
			return;
		}
		String dateString = date.getText().toString();
		if (dateString == null) {
			return;
		}
		String timeString = time.getText().toString();
		if (timeString == null) {
			return;
		}
		try {
			final AndroidPlan plan = new AndroidPlan();
			plan.setDate(new SimpleDateFormat("MMM d, yyyy H:m").parse(dateString + " " + timeString));
			plan.setName(name);
			plan.setLocation(location);
			plan.setDescription(description);
			plan.setUser(UserUtil.user);
			
			
			final ProgressDialog dialog = new ProgressDialog(AddPlanActivity.this);
			dialog.setMessage("Adding new plan...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					HttpJsonRpcClientTransport transport;
					try {
						transport = new HttpJsonRpcClientTransport(new URL(UserUtil.planServiceUrl));
						JsonRpcInvoker invoker = new JsonRpcInvoker();
						PlanService calc = invoker.get(transport, "plan", PlanService.class);

						AndroidPlan newPlan = calc.addPlan(plan);
						
						if (UserUtil.allPlans != null) {
							AndroidPlan[] newPlans = new AndroidPlan[UserUtil.allPlans.length + 1];
							int i = 0;
							for (AndroidPlan p : UserUtil.allPlans) {
								newPlans[i] = p;
								i++;
							}
							newPlans[UserUtil.allPlans.length] = newPlan;
							UserUtil.allPlans = newPlans;
						}
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					AddPlanActivity.this.runOnUiThread(new Runnable() {
						public void run() {

							dialog.dismiss();
							CharSequence text = "Plan was added successfully";
							int duration = Toast.LENGTH_LONG;
							Toast toast = Toast.makeText(getApplicationContext(), text, duration);
							toast.show();
							
							finish();
						}
					});
				}
			}).start();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
